<template>
  <page-header-wrapper :title="false">
    <a-card :bordered="false" :style="{margin:'0 -24px',padding:0}">
      <!-- 新建 -->
      <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>
      <!-- 查询表单 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="4" :sm="24">
              <a-form-item label="商家名字">
                <a-input :allowClear="true" v-model="queryParam.shop_name" placeholder="请输入商家名字"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="核销手机">
                <a-input :allowClear="true" v-model="queryParam.mobile" placeholder="请输入核销手机"/>
              </a-form-item>
            </a-col>
            <a-col :md="7" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="handleSearch">查询</a-button>
                <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 表格 -->
      <a-spin :spinning="loading">
        <a-table :dataSource="cardListData" :columns="cardListColumns" rowKey="id">
          <span slot="address" slot-scope="text, record">
            <template>
              <span>{{ record.area_info + record.address }}</span>
            </template>
          </span>
          <span slot="status" slot-scope="text, record">
            <template>
              <span>{{ record.status == 1? '启用' : '禁用' }}</span>
            </template>
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical"/>
              <a @click="btnStatus(record)">{{ record.status == 1? '禁用' : '启用' }}</a>
              <a-divider type="vertical"/>
              <a @click="btnDel(record)">删除</a>
            </template>
          </span>
        </a-table>
      </a-spin>
      <!-- 新增商家弹出模板 -->
      <a-modal v-model="addVisible" title="新增商家" @ok="handleOk" @cancel="handleCancel" width="800px">
          <a-form v-bind="formLayout" v-if="mobileIsChecked == 0">
            <a-form-item label="店铺名称" required>
              <a-input placeholder="请输入店铺名称" v-model="formData.shop_name" :maxLength="11" style="width:250px;margin-right: 20px;" />
            </a-form-item>
            <a-form-item label="联系电话" required>
              <a-input placeholder="请输入联系电话" v-model="formData.mobile" :maxLength="11" style="width:250px;margin-right: 20px;"/>
            </a-form-item>
            <a-form-item label="商家地址" required>
              <a-cascader
                v-model="address"
                allowClear
                :options="homeOptions"
                change-on-select
                placeholder="请选择地址"
                @change="areaChange"
                :field-names="{ label: 'region_name', value: 'region_id', children: 'children' }"
                :load-data="loadData"
                style="width: 250px;"
              />
						</a-form-item>
            <a-form-item label="详细地址" required>
              <a-input placeholder="请输入详细地址" v-model="formData.address" :maxLength="50" style="width:250px;margin-right: 20px;"/>
            </a-form-item>
            <a-form-item label="优惠规则">
              <a-input placeholder="请输入优惠规则" v-model="formData.role" :maxLength="50" style="width:250px;margin-right: 20px;"/>
            </a-form-item>
            <a-form-item label="经纬度" required>
              <a-button type="primary" style="margin-left: 10px;border-radius: 6px;" @click="getCoordinate">获取经纬度</a-button>
            </a-form-item>
            <a-form-item style="margin-left: 60px;font-weight: bold;">
              <span>经度：{{ formData.lng }}</span>
              <span>纬度：{{ formData.lat }}</span>
            </a-form-item>
          </a-form>
      </a-modal>
      <!-- 删除弹窗 -->
      <a-modal v-model="delVisible" title="提示" @ok="handleDel" @cancel="handleDelCancel">
          <span>您确定要删除吗？一经删除，无法恢复！</span>
      </a-modal>
      <!-- 编辑商家弹出模板 -->
      <a-modal v-model="editVisible" title="编辑商家" @ok="handleEditOk" @cancel="handleCancel" width="800px">
          <a-form v-bind="formLayout" v-if="mobileIsChecked == 0">
            <a-form-item label="店铺名称" required>
              <a-input placeholder="请输入店铺名称" v-model="editData.shop_name" :maxLength="11" style="width:250px;margin-right: 20px;" />
            </a-form-item>
            <a-form-item label="联系电话" required>
              <a-input placeholder="请输入联系电话" v-model="editData.mobile" :maxLength="11" style="width:250px;margin-right: 20px;"/>
            </a-form-item>
            <a-form-item label="商家地址" required>
              <a-cascader
                v-model="address"
                allowClear
                :options="homeOptions"
                change-on-select
                :placeholder="editAddress"
                @change="areaChange"
                :field-names="{ label: 'region_name', value: 'region_id', children: 'children' }"
                :load-data="loadData"
                style="width: 250px;"
              />
						</a-form-item>
            <a-form-item label="详细地址" required>
              <a-input placeholder="请输入详细地址" v-model="editData.address" :maxLength="50" style="width:250px;margin-right: 20px;"/>
            </a-form-item>
            <a-form-item label="优惠规则">
              <a-input placeholder="请输入优惠规则" v-model="editData.role" :maxLength="50" style="width:250px;margin-right: 20px;"/>
            </a-form-item>
            <a-form-item label="经纬度" required>
              <a-button type="primary" style="margin-left: 10px;border-radius: 6px;" @click="getEditCoordinate">获取经纬度</a-button>
            </a-form-item>
            <a-form-item style="margin-left: 60px;font-weight: bold;">
              <span>经度：{{ editData.lng }}</span>
              <span>纬度：{{ editData.lat }}</span>
            </a-form-item>
          </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>
<script>
import { notification } from 'ant-design-vue'
import { getVillageList, updateStoreStatus, getStoreList, btnRegionList, addShop, getStoreDetail, editStore } from '@/api/card'
import Map from './modules/Map.vue'
export default {
  components: {
    Map
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      }
    }
    return {
      mapVisible: false,
      mapPosition: null,
      mapAddress: '',
      // 商铺地址
      address: [],
      // 省市区配置
      homeOptions: [],
      formData: {
        mobile: undefined, // 商家登录手机
        shop_name: undefined, // 商家名字
        role: undefined, // 优惠规则
        province_id: undefined, // 省ID
        city_id: undefined, // 市ID
        area_id: undefined, // 区ID
        area_info: undefined, // 区域信息
        lat: undefined, // 纬度
        lng: undefined, // 经度
        address: undefined // 详细地址
      },
      editData: {
        mobile: undefined, // 商家登录手机
        shop_name: undefined, // 商家名字
        role: undefined, // 优惠规则
        province_id: undefined, // 省ID
        city_id: undefined, // 市ID
        area_id: undefined, // 区ID
        area_info: undefined, // 区域信息
        lat: undefined, // 纬度
        lng: undefined, // 经度
        address: undefined // 详细地址
      },
      queryParam: {
        shop_name: undefined,
        mobile: undefined
      },
      villageList: [],
      addVisible: false,
      // 手机验证正则
      mobileRule: /^1[3456789]\d{9}$/,
      // 手机号检测状态
      mobileIsChecked: 0,
      // 表格数据
      cardListData: [],
      // 表头
      cardListColumns: [
        {
          title: 'ID',
          dataIndex: 'id',
          align: 'center'
        },
        {
          title: '商家名字',
          dataIndex: 'shop_name',
          align: 'center'
        },
        {
          title: '店铺地址',
          dataIndex: 'village_name',
          align: 'center',
          scopedSlots: { customRender: 'address' }
        },
        {
          title: '核销手机',
          dataIndex: 'mobile',
          align: 'center'
        },
        {
          title: '商家账号',
          dataIndex: 'nickname',
          align: 'center'
        },
        {
          title: '优惠规则',
          dataIndex: 'role',
          align: 'center'
        },
        {
          title: '卡片状态',
          dataIndex: 'status',
          align: 'center',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 检测手机号后获得的用户信息
      userMes: {},
      // 村庄列表
      villageChooseList: [],
      // 删除弹窗开关
      delVisible: false,
      // 卡片信息
      cardMes: {},
      // 加载开关
      loading: true,
      // 使用记录开关
      editVisible: false,
      // 使用记录列表
      historyListData: [],
      popupVisible: null,
      address_info: undefined,
      // 经纬度获取状态
      lnglatStatus: 0,
      editAddress: '',
      editAddressArray: [],
      editId: undefined
    }
  },
  methods: {
    setMap (data) {
      console.log(data)
      this.mapPosition = data.position
      this.mapAddress = data.address
      this.mapVisible = false
    },
    // 获取商家列表
    btnGetList () {
      const from = {
        page: 1,
        per_page: 10
      }
      getStoreList(from).then(res => {
        this.cardListData = res.data
        this.loading = false
      })
    },
    // 新增村民-打开弹窗
    handleAdd () {
      this.addVisible = true
    },
    // 编辑商家-打开弹窗并获取详情
    handleEdit (data) {
      this.editVisible = true
      this.editId = data.id
      const from = {
        id: data.id
      }
      getStoreDetail(from).then(res => {
        console.log(res)
        this.editData.shop_name = res.shop_name
        this.editData.mobile = res.mobile
        this.editData.address = res.address
        this.editData.role = res.role
        this.editData.lat = res.lat
        this.editData.lng = res.lng
        this.editAddress = res.area_info
        this.editAddressArray = [res.province_id, res.city_id, res.area_id]
      })
    },
    // 编辑商家确认回调
    handleEditOk () {
      if (this.editData.area_info == undefined || this.editData.area_info == '') {
        this.editData.area_info = this.editAddress
        this.editData.province_id = this.editAddressArray[0]
        this.editData.city_id = this.editAddressArray[1]
        this.editData.area_id = this.editAddressArray[2]
      } else {
        console.log(this.editData.address_info)
        this.editData.area_info = this.address_info[0].region_name + this.address_info[1].region_name + this.address_info[2].region_name
        this.editData.province_id = this.address[0]
        this.editData.city_id = this.address[1]
        this.editData.area_id = this.address[2]
      }
      if (this.editData.shop_name == undefined || this.editData.shop_name == '') {
        notification.open({
          type: 'warning',
          message: '提示',
          description: '请填写商家名字！'
        })
        return
      }
      if (this.editData.mobile == undefined || this.editData.mobile == '') {
        notification.open({
          type: 'warning',
          message: '提示',
          description: '请填写联系电话！'
        })
        return
      }
      if (this.editData.address == undefined || this.editData.address == '') {
        notification.open({
          type: 'warning',
          message: '提示',
          description: '请填写详细地址！'
        })
        return
      }
      if (this.lnglatStatus == 0) {
        notification.open({
          type: 'warning',
          message: '提示',
          description: '请获取经纬度！'
        })
        return
      }
      const from = {
        ...this.editData,
        id: this.editId
      }
      editStore(from).then(res => {
        this.editVisible = false
      })
      notification.open({
          type: 'success',
          message: '提示',
          description: '修改成功！'
      })
      setTimeout(() => {
        this.btnGetList()
      }, 1000)
    },
    // 获取省市区一级数据
    getRegionList () {
				const from = {
					region_id: undefined
				}
				btnRegionList(from).then((res) => {
          this.homeOptions = res.region_list.map(item => {
            item.isLeaf = false // 获取父级分类，为每一项添加isLeaf，这样才能动态去加载
            return item
          })
          this.homeOptions = res.region_list
				})
		},
    // 地址改变
    areaChange (value, label) {
      this.address = value
      this.address_info = label
    },
    // loadData
    async loadData (e) {
      const targetOption = e[e.length - 1]
      targetOption.loading = true
      if (this.address.length == 3) {
        targetOption.loading = false
        this.popupVisible = false
      } else {
        const from = { region_id: this.address[this.address.length - 1] }
        const res = await btnRegionList(from)
        // console.log(res)
        if (res.region_list.length == 0) {
          targetOption.loading = false
          return
        }

        res.region_list.forEach(item => {
          item.isLeaf = false
          targetOption.loading = false
        })
        targetOption.children = [...res.region_list]
        this.homeOptions = [...this.homeOptions]
      }
    },
    showPosition (data) {
      console.log(data)
      this.formData.lat = data.latitude
      this.formData.lng = data.longitude
    },
    // 新增获取经纬度
    getCoordinate () {
      var _this = this
      _this.lnglatStatus = 1
      _this.formData.area_info = _this.address_info[0].region_name + _this.address_info[1].region_name + _this.address_info[2].region_name
      var address = _this.formData.area_info + _this.formData.address
      var geocoder = new AMap.Geocoder({
        // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        city: '全国'
      })
      geocoder.getLocation(address, function (status, result) {
        if (status === 'complete' && result.geocodes.length) {
          var lnglat = result.geocodes[0].location
          console.log(lnglat)
          _this.formData.lat = lnglat.lat
          _this.formData.lng = lnglat.lng
        } else {
          console.error('根据地址查询位置失败', status, result)
        }
      })
    },
    // 编辑商家获取经纬度
    getEditCoordinate () {
      var _this = this
      _this.lnglatStatus = 1
      if (_this.address == undefined || _this.address == '') {
        var address = _this.editAddress
      } else {
        _this.editData.area_info = _this.address_info[0].region_name + _this.address_info[1].region_name + _this.address_info[2].region_name
        address = _this.editData.area_info + _this.editData.address
      }
      console.log(address)
      var geocoder = new AMap.Geocoder({
        // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        city: '全国'
      })
      geocoder.getLocation(address, function (status, result) {
        if (status === 'complete' && result.geocodes.length) {
          var lnglat = result.geocodes[0].location
          console.log(lnglat)
          _this.editData.lat = lnglat.lat
          _this.editData.lng = lnglat.lng
        } else {
          console.error('根据地址查询位置失败', status, result)
        }
      })
    },
    // 新增商家确认回调
    handleOk () {
      this.formData.province_id = this.address[0]
      this.formData.city_id = this.address[1]
      this.formData.area_id = this.address[2]
      console.log(this.formData)
      if (this.formData.shop_name == undefined || this.formData.shop_name == '') {
        notification.open({
          type: 'warning',
          message: '提示',
          description: '请填写商家名字！'
        })
        return
      }
      if (this.formData.mobile == undefined || this.formData.mobile == '') {
        notification.open({
          type: 'warning',
          message: '提示',
          description: '请填写联系电话！'
        })
        return
      }
      if (this.formData.mobile == undefined || this.formData.mobile == '') {
        notification.open({
          type: 'warning',
          message: '提示',
          description: '请填写联系电话！'
        })
        return
      }
      if (this.formData.province_id == undefined || this.formData.city_id == undefined || this.formData.area_id == undefined || this.formData.province_id == '' || this.formData.city_id == '' || this.formData.area_id == '') {
        notification.open({
          type: 'warning',
          message: '提示',
          description: '请输入省市区！'
        })
        return
      }
      if (this.formData.address == undefined || this.formData.address == '') {
        notification.open({
          type: 'warning',
          message: '提示',
          description: '请填写详细地址！'
        })
        return
      }
      if (this.lnglatStatus == 0) {
        notification.open({
          type: 'warning',
          message: '提示',
          description: '请获取经纬度！'
        })
        return
      }
      addShop(this.formData).then(res => {
        this.addVisible = false
        notification.open({
          type: 'success',
          message: '提示',
          description: '新增成功！'
        })
        this.handleCancel()
      }).catch(() => {
        this.addVisible = false
      })

      setTimeout(() => {
        this.btnGetList()
      }, 1000)
    },
    // 新增村民关闭回调
    handleCancel () {
      this.mobileIsChecked = 0
      this.formData.mobile = undefined
      this.formData.shop_name = undefined // 商家名字
      this.formData.role = undefined // 优惠规则
      this.formData.province_id = undefined // 省ID
      this.formData.city_id = undefined // 市ID
      this.formData.area_id = undefined // 区ID
      this.formData.area_info = undefined // 区域信息
      this.formData.lat = undefined // 纬度
      this.formData.lng = undefined // 经度
      this.formData.address = undefined
      this.address = undefined // 详细地址
      this.userMes = {}
    },
    // 点击删除链接
    btnDel (data) {
      this.delVisible = true
      this.cardMes = data
      this.editId = data.id
    },
    // 确认删除回调
    handleDel () {
      const from = {
        id: this.editId,
        status: 3
      }
      updateStoreStatus(from).then(res => {
        notification.open({
          type: 'success',
          message: '提示',
          description: '删除成功！'
      })
      setTimeout(() => {
        this.delVisible = false
        this.btnGetList()
      }, 1000)
      })
    },
    // 取消删除回调
    handleDelCancel () {
      this.delVisible = false
    },
    // 启用与禁用
    btnStatus (data) {
      if (data.status == 1) {
        const from = {
          id: data.id,
          status: 2
        }
        updateStoreStatus(from).then(() => {
          this.btnGetList()
          notification.open({
          type: 'success',
          message: '提示',
          description: '禁用成功！'
      })
        }).catch(() => {
          this.btnGetList()
        })
      } else {
        const from = {
          id: data.id,
          status: 1
        }
        updateStoreStatus(from).then(() => {
          this.btnGetList()
          notification.open({
          type: 'success',
          message: '提示',
          description: '启用成功！'
      })
        }).catch(() => {
          this.btnGetList()
        })
      }
    },
    // 查询
    handleSearch () {
      console.log(this.queryParam)
      const from = {
        ...this.queryParam,
        page: 1,
        per_page: 10
      }
      getStoreList(from).then(res => {
        this.cardListData = res.data
        this.loading = false
      })
    },
    // 获取全部村庄
    getAllVillage () {
      getVillageList().then(res => {
        this.villageChooseList = res.list
      })
    },
    // 重置
    handleReset () {
      this.queryParam.shop_name = undefined
      this.queryParam.mobile = undefined
      this.btnGetList()
    }
  },
  async mounted () {
    this.btnGetList()
    this.getAllVillage()
    this.getRegionList()
  }
}
</script>
